package com.xingfudazi.web.ai;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.xingfudazi.app.domain.AppAccount;
import com.xingfudazi.app.domain.AppMember;
import com.xingfudazi.app.service.IAppAccountService;
import com.xingfudazi.app.service.IAppMemberService;
import com.xingfudazi.app.service.domain.WxRequestService;
import com.xingfudazi.common.core.domain.AjaxResult;
import com.xingfudazi.common.core.domain.Result;
import com.xingfudazi.common.utils.JSONUtil;
import com.xingfudazi.common.utils.SecurityUtils;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.rmi.CORBA.Util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author YuJiaMing
 * date 2024年08月01日 14:42
 */
@RestController
@RequestMapping("ai")
public class AIController {

    @Autowired
    private IAppMemberService appMemberService;

    @Autowired
    private IAppAccountService appAccountService;

    @Autowired
    private WxRequestService wxRequestService;

    /*
     * 泄露出去可要犯杀头之罪
     */
    static {
        Constants.apiKey = "sk-d47a0b513965440186d8ee8148cba8db";
    }

    /**
     * 5分钟缓存
     * 最多1000个
     */
    private static final Cache<Long, List<Message>> CACHE = CacheBuilder.newBuilder()
            .expireAfterAccess(5, TimeUnit.MINUTES)
            .maximumSize(1000)
            .build();

    /**
     * 模型的名字
     */
    private static final String MODEL_NAME = "qwen2.5-72b-instruct";


    private static final Generation GEN = new Generation();


    private static Message createMessage(String content) {
        return Message.builder().role(Role.USER.getValue()).content(content).build();
    }

    private boolean checkRisk(Map<String, ?> response, String content) {
        if (content == null || content.isEmpty()) {
            return false;
        }

        Integer errorCode = (Integer) response.get("errcode");
        if (errorCode == null || errorCode != 0) {
            // Handle error code not being 0 or missing
            return true; // Assuming an error is considered a risk
        }

        @SuppressWarnings("unchecked")
        List<Map<String, ?>> detail = (List<Map<String, ?>>) response.get("detail");

        if (detail == null || detail.isEmpty()) {
            // No details provided, consider as no risk
            return false;
        }

        return detail.stream()
                .filter(item -> "content_model".equals(item.get("strategy")))
                .anyMatch(item -> {
                    Object labelObj = item.get("label");
                    return labelObj instanceof Integer && ((Integer) labelObj) != 100;
                });
    }

    /**
     * 消息
     */
    @PostMapping("message")
    public Result<?> message(String message) throws Exception {
        Long userId = SecurityUtils.getUserId();

        if (userId == null) {
            return Result.success("您好亲！ 登录了才能跟我聊天哦");
        }

        // 风控内容
        AppMember appMember = appMemberService.getById(userId);
        Long aid = appMember.getAid();
        AppAccount appAccount = appAccountService.selectAppAccountById(aid);
        String openId = appAccount.getWxOpenId();
        // 使用该方法来检查 nickname 的风险检测
        Map<String, ?> resNickName = (Map<String, ?>) wxRequestService.riskText(message, openId);
        if (checkRisk(resNickName, message)) {
            return Result.success("当前内容存在风险");
        }

        List<Message> messages = CACHE.get(userId, ArrayList::new);
        messages.add(createMessage(message));

        GenerationParam param = GenerationParam.builder()
                .model(MODEL_NAME)
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .prompt("你是一个情感博主，可以解答别人心中的情感困惑，分析提问的人心中的疑问。当别人问你是谁的时候，你要回答你是一个情感专家。")
                .build();


        GenerationResult result = GEN.call(param);
        Message answer = result.getOutput().getChoices().get(0).getMessage();
        messages.add(answer);
        return Result.success(answer.getContent());
    }


    public static void main(String[] args) throws NoApiKeyException, InputRequiredException {
        return;
    }

}
